﻿(function ($) {

    $.util.namespace("mainpage.nav");
    $.util.namespace("mainpage.mainTabs");
    $.util.namespace("mainpage.configinfo");

    var homeLayout = "#home-layout", nowTimeLabelId = "#nowTime", northTopbar = "#north-topbar", northToolbar = "#north-toolbar", themeSelector = "#themeSelector",
        westLayout = "#westLayout", westCenterLayout = "#westCenterLayout", navTab = "#navTab", westSouthPanel = "#westSouthPanel", navMenuList = "#navMenu_list", navMenuTree = "#navMenu_Tree",
        homePageTitle = "主页", homePageHref = null, mainTab = "#mainTab", homePanel = "#homePanel";



    //刷新屏幕右上角的当前时间显示的标签。
    window.mainpage.beginAutoRefreshNowTimeLabel = function () {
        var refresh = function () { $(nowTimeLabelId).text($.date.toLongDateTimeString(new Date())); };
        refresh();
        window.setInterval(refresh, 1000);
    };

    //绑定主界面工具栏按钮事件。
    window.mainpage.bindMainFormButtonBarEvent = function (northCollapse) {
        //修改密码
        $("a#a3", "#buttonbar").click(function () {
            $.post("/Account/TestForError", function (result) {
                window.jeasyui.helper.actionDoneCallBack.call(this, result);
            });
            //window.mainpage.passwordModify();
        });
        //注销登录
        //$("a#a5", "#buttonbar").click(function () {
        //    window.mainpage.logoutConfirmAndExit(function () { $.easyui.loading({ locale: $("body"), msg: "正在注销，请稍等..." }); });
        //});

        //隐藏顶部栏按钮事件
        $("#btnHideNorth").click(function () { window.mainpage.hideNorth(); });
        //显示顶部栏按钮事件
        var btnShow = $("#btnShowNorth").click(function () { window.mainpage.showNorth(); });
        var north = $(homeLayout).layout("panel", "north"), panel = north.panel("panel"),
            toolbar = $(northToolbar), topbar = $(northTopbar), top = toolbar.css("top"),
            opts = north.panel("options"), onCollapse = opts.onCollapse, onExpand = opts.onExpand;
        opts.onCollapse = function () {
            if ($.isFunction(onCollapse)) { onCollapse.apply(this, arguments); }
            btnShow.show();
            toolbar.insertBefore(panel).css("top", 0).addClass("top-toolbar-topmost");
            window.mainpage.configinfo.setHomeLayoutState("north", true);
        };
        opts.onExpand = function () {
            if ($.isFunction(onExpand)) { onExpand.apply(this, arguments); }
            btnShow.hide();
            toolbar.insertAfter(topbar).css("top", top).removeClass("top-toolbar-topmost");
            window.mainpage.configinfo.setHomeLayoutState("north", false);
        };
        if (northCollapse) {
            btnShow.show();
            toolbar.insertBefore(panel).css("top", 0).addClass("top-toolbar-topmost");
        }
        //左边栏、底部栏的折叠展开事件
        var west = $(homeLayout).layout("panel", "west");
        opts1 = west.panel("options"), onCollapse1 = opts1.onCollapse, onExpand1 = opts1.onExpand;
        opts1.onCollapse = function () {
            if ($.isFunction(onCollapse1)) { onCollapse1.apply(this, arguments); }
            window.mainpage.configinfo.setHomeLayoutState("west", true);
        };
        opts1.onExpand = function () {
            if ($.isFunction(onExpand1)) { onExpand1.apply(this, arguments); }
            window.mainpage.configinfo.setHomeLayoutState("west", false);
        };

        var south = $(homeLayout).layout("panel", "south");
        opts2 = south.panel("options"), onCollapse2 = opts2.onCollapse, onExpand2 = opts2.onExpand;
        opts2.onCollapse = function () {
            if ($.isFunction(onCollapse2)) { onCollapse2.apply(this, arguments); }
            window.mainpage.configinfo.setHomeLayoutState("south", true);
        };
        opts2.onExpand = function () {
            if ($.isFunction(onExpand2)) { onExpand2.apply(this, arguments); }
            window.mainpage.configinfo.setHomeLayoutState("south", false);
        };

        //皮肤风格选择列表事件绑定
        $(themeSelector).combobox({
            width: 140,
            editable: false,
            data: $.easyui.theme.dataSource,
            valueField: "path", textField: "name",
            onSelect: function (record) {
                var opts = $(this).combobox("options");
                window.mainpage.setTheme(record[opts.valueField])
            }
        });
    };

    window.mainpage.hideNorth = function () { $(homeLayout).layout("collapse", "north"); };

    window.mainpage.showNorth = function () { $(homeLayout).layout("expand", "north"); };

    window.mainpage.setTheme = function (theme) {
        $.easyui.theme(true, theme, function (item) {
            var win = $.easyui.messager.show($.string.format("您设置了新的系统主题皮肤为：{0}，{1}。", item.name, item.path));
            if ($.util.browser.msie) { win.removeAttr("style"); }
            window.mainpage.configinfo.setDefaultTheme(item.path);
        });
    };






    //  初始化应用程序主界面左侧面板中“导航菜单”的数据，并加载特定的子菜单树数据。
    window.mainpage.instMainMenus = function (rootMenuId) {
        window.mainpage.loadNavMenus(rootMenuId);
        window.mainpage.instNavTree();
    };

    //  将指定的根节点数据集合数据加载至左侧面板中“导航菜单”的 ul 控件中；该方法定义如下参数：
    //      rootMenuId: 默认打开的主功能菜单ID值
    window.mainpage.loadNavMenus = function (rootMenuId) {
        var ul = $(navMenuList).empty(), menus;
        window.mainpage.authmenus.getRootMenus(function (data) {
            menus = data;
            $.each(menus, function (i, item) {
                var li = $("<li></li>").appendTo(ul);
                var pp = $("<div></div>").addClass("panel-header panel-header-noborder").appendTo(li);
                var a = $("<a></a>").attr({ href: "javascript:void(0);", target: "_self", key: item.ID, keycode: item.Code }).hover(function () {
                    a.addClass("tree-node-selected");
                }, function () {
                    if (!a.hasClass("selected")) { $(this).removeClass("tree-node-selected"); }
                }).click(function () {
                    a.closest("ul").find("a").removeClass("tree-node-selected selected");
                    a.addClass("tree-node-selected selected");
                    var key = $(this).attr("key");
                    var code = $(this).attr("keycode");
                    window.mainpage.setUserDefaultMasterMenuKey(key);
                    window.mainpage.loadMenu(item.ID, code);
                }).appendTo(pp);
                var span = $("<span></span>").addClass("nav-menu").appendTo(a);
                $("<span></span>").addClass("nav-menu-icon" + (item.IconCls ? " " + item.IconCls : " icon-unknow")).text(item.Name).appendTo(span);
            });
            var layout = $(westLayout), south = layout.layout("panel", "south"), southOpts = south.panel("options");
            southOpts.minHeight = 5 + Math.min(menus.length, 3) * 27; southOpts.maxHeight = 5 + menus.length * 27;
            layout.layout("resize");
            window.mainpage.loadDefaultMenuMainData(rootMenuId);
        });
    };

    //  初始化 westSouthPanel 位置的“导航菜单”区域子菜单 ul 控件(仅初始化 easyui-tree 对象，不加载数据)。
    window.mainpage.instNavTree = function () {
        var t = $(navMenuTree).tree({
            toggleOnClick: true,
            dataPlain: true,
            parentField: "ParentID",
            animate: true,
            lines: false,
            enableContextMenu: false,
            onClick: function (node) {
                if (!node || !node.attributes || !node.attributes.href || $.string.isNullOrWhiteSpace(node.attributes.href)) { return; }
                window.mainpage.mainTabs.addModule(node.attributes);
            },
            onLoadSuccess: function (node, data) {
                $.util.exec(function () { $(navMenuList).find("a").removeAttr("disabled"); });
                $.easyui.loaded($(westCenterLayout));
            }
        });
    };

    //  按照指定的根节点菜单 id，加载其相应的子菜单树面板数据；该方法定义如下参数：
    //      id: 表示根节点菜单的 id；
    //      code: 表示根节点菜单的 code
    window.mainpage.loadMenu = function (id, code) {
        $(navMenuList).find("a").attr("disabled", true);
        $.easyui.loading({ locale: westCenterLayout });
        window.mainpage.authmenus.getChildrenMenus(id, code, function (data) {
            $(navMenuTree).tree("loadData", data);
        });
    };


    //设置当前用户加载系统主页面时默认打开的主功能菜单Key值。
    window.mainpage.setUserDefaultMasterMenuKey = function (key) {
        window.mainpage.configinfo.setDefaultRootMenu(key);
    };

    //在界面菜单数据绑定完后加载默认的菜单树节点内容。
    window.mainpage.loadDefaultMenuMainData = function (rootMenuId) {
        var key = rootMenuId;
        var a = $(navMenuList).find("a[key='" + key + "']");
        if (a.length == 0) {
            a = $(navMenuList).find("a:first");
        }
        if (a.length != 0) {
            a.closest("ul").find("a").removeClass("tree-node-selected selected");
            a.addClass("tree-node-selected selected");
            window.mainpage.loadMenu(a.attr("key"), a.attr("keycode"));
        }
    };

    window.mainpage.bindNavTabsButtonEvent = function () {
        //tabs工具按钮-刷新
        $("#navMenu_refresh").click(function () { window.mainpage.nav.refreshTree(); });
    };



    window.mainpage.refreshNavTab = function (index) {
        var t = $(navTab);
        if (index == null || index == undefined) { index = t.tabs("getSelectedIndex"); }
        if (index == 0) { window.mainpage.nav.refreshNav(); }
    };
    window.mainpage.nav.refreshNav = function () { window.mainpage.instMainMenus(); };
    window.mainpage.nav.refreshTree = function () { $(navMenuList).find("a.tree-node-selected.selected").click(); };

    //添加主页tab
    window.mainpage.addMainTab = function () {
        $(mainTab).tabs("add", { title: "主页", iconCls: "icon-hamburg-home", repeatable: true, iniframe: true, bodyCls: "BigIframe", href: "/Desk/Index", selected: true });
    };

    //  判断指定的选项卡是否存在于当前主页面的选项卡组中；
    //  返回值：返回的值可能是以下几种：
    //      0:  表示不存在于当前选项卡组中；
    //      1:  表示仅 title 值存在于当前选项卡组中；
    //      2:  表示 title 和 href 都存在于当前选项卡组中；
    window.mainpage.mainTabs.isExists = function (title, href) {
        var t = $(mainTab), tabs = t.tabs("tabs"), array = $.array.map(tabs, function (val) { return val.panel("options"); }),
            list = $.array.filter(array, function (val) { return val.title == title; }), ret = list.length ? 1 : 0;
        if (ret && $.array.some(list, function (val) { return val.href == href; })) { ret = 2; }
        return ret;
    };

    window.mainpage.mainTabs.tabDefaultOption = {
        title: "新建选项卡", href: "", iniframe: true, closable: true, refreshable: true, iconCls: "icon-standard-tab", selected: true, bodyCls: 'BigIframe'
    };
    window.mainpage.mainTabs.parseCreateTabArgs = function (args) {
        var ret = {};
        if (args.length == 0) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption); }
        if (args.length == 1) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, typeof args[0] == "object" ? args[0] : { href: args[0] }); }
        if (args.length == 2) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1] }); }
        if (args.length == 3) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2] }); }
        if (args.length == 4) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3] }); }
        if (args.length == 5) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4] }); }
        if (args.length == 6) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4], refreshable: args[5] }); }
        if (args.length == 7) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4], refreshable: args[5], selected: args[6] }); }
        return ret;
    };

    window.mainpage.mainTabs.createTab = function (title, href, iconCls, iniframe, closable, refreshable, selected) {
        var t = $(mainTab), i = 0, opts = window.mainpage.mainTabs.parseCreateTabArgs(arguments);
        while (t.tabs("getTab", opts.title + (i ? String(i) : ""))) { i++; }
        t.tabs("add", opts);
    };

    //  添加一个新的模块选项卡；该方法重载方式如下：
    //      function (tabOption)
    //      function (href)
    //      function (title, href)
    //      function (title, href, iconCls)
    //      function (title, href, iconCls, iniframe)
    //      function (title, href, iconCls, iniframe, closable)
    //      function (title, href, iconCls, iniframe, closable, refreshable)
    //      function (title, href, iconCls, iniframe, closable, refreshable, selected)
    window.mainpage.mainTabs.addModule = function (title, href, iconCls, iniframe, closable, refreshable, selected) {
        var opts = window.mainpage.mainTabs.parseCreateTabArgs(arguments), isExists = window.mainpage.mainTabs.isExists(opts.title, opts.href);
        switch (isExists) {
            case 0: window.mainpage.mainTabs.createTab(opts); break;
            case 1: window.mainpage.mainTabs.createTab(opts); break;
            case 2: window.mainpage.mainTabs.jumeTab(opts.title); break;
            default: break;
        }
    };

    window.mainpage.mainTabs.jumeTab = function (which) { $(mainTab).tabs("select", which); };

    window.mainpage.mainTabs.jumpHome = function () {
        var t = $(mainTab), tabs = t.tabs("tabs"), panel = $.array.first(tabs, function (val) {
            var opts = val.panel("options");
            return opts.title == homePageTitle && opts.href == homePageHref;
        });
        if (panel && panel.length) {
            var index = t.tabs("getTabIndex", panel);
            t.tabs("select", index);
        }
    }






    window.mainpage.configinfo.setDefaultRootMenu = function (key) {
        $.util.requestAjaxData("/Home/SetDefaultRootMenu", { id: key });
    };

    window.mainpage.configinfo.setDefaultTheme = function (name) {
        $.util.requestAjaxData("/Home/SetDefaultTheme", { name: name });
    };

    window.mainpage.configinfo.setHomeLayoutState = function (region, collapse) {
        if ($.array.contains(["north", "west", "south"], region)) {
            $.post("/Home/SetHomeLayoutState", { region: region, collapse: collapse });
        }
    };

    window.startup = function (northCollapse, lastRootMenuId, lastTheme) {
        window.mainpage.beginAutoRefreshNowTimeLabel();
        window.mainpage.bindMainFormButtonBarEvent(northCollapse);
        window.mainpage.instMainMenus(lastRootMenuId);
        window.mainpage.bindNavTabsButtonEvent();

        var layout = $("#home-layout"), navTab = $("#navTab"), themeCombo = $("#themeSelector");

        $.util.exec(function () {

            layout.removeClass("hidden").layout("resize");

            window.mainpage.addMainTab();

            var theme = $.easyui.theme();
            if (lastTheme && lastTheme != theme) { window.mainpage.setTheme(lastTheme); }
            themeCombo.combobox("setValue", lastTheme || $.easyui.theme.dataSource[0].path);

            $("#maskContainer").remove();
        });
    };

})(jQuery);